package com.neihe.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.neihe.common.base.ApiException;
import com.neihe.common.constant.Const;
import com.neihe.common.enums.DelFlagEnum;
import com.neihe.entity.UserFile;
import com.neihe.entity.dto.file.DeleteFileDTO;
import com.neihe.entity.dto.file.QueryFileListContextDTO;
import com.neihe.entity.dto.file.RestoreFileDTO;
import com.neihe.entity.vo.file.UserFileVO;
import com.neihe.listenner.event.DeleteFileEvent;
import com.neihe.listenner.event.RestoreFileEvent;
import com.neihe.service.IRecycleService;
import com.neihe.service.IUserFileService;
import com.neihe.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class RecycleServiceImpl implements IRecycleService, ApplicationContextAware {

    @Autowired
    private IUserFileService userFileService;

    @Autowired
    private IUserService userService;

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public List<UserFileVO> recycles(Long userId) {
        QueryFileListContextDTO queryFileListContextDTO = new QueryFileListContextDTO();
        queryFileListContextDTO.setUserId(userId);
        queryFileListContextDTO.setDelFlag(DelFlagEnum.YES.getCode());
        return userFileService.getFileList(queryFileListContextDTO);
    }

    @Override
    public void restore(RestoreFileDTO requestParam) {
        List<Long> fileIds = requestParam.getFileIds();
        List<UserFile> records = userFileService.listByIds(fileIds);

        if (CollUtil.isEmpty(records)) {
            throw new ApiException("内部错误，文件还原失败");
        }

        Set<Long> userIdSet = records.stream().map(UserFile::getUserId).collect(Collectors.toSet());
        if (userIdSet.size() > 1) {
            throw new ApiException("无权执行文件还原");
        }

        Long userId = StpUtil.getLoginIdAsLong();
        if (!userIdSet.contains(userId)) {
            throw new ApiException("无权执行文件还原");
        }

        Set<String> filenameSet = records.stream()
                .map(record -> record.getFilename() + Const.COMMON_SEPARATOR + record.getParentId())
                .collect(Collectors.toSet());

        if (filenameSet.size() != records.size()) {
            throw new ApiException("文件还原失败，该还原文件中存在同名文件，请逐个还原并重命名");
        }

        for (UserFile record : records) {
            QueryWrapper<UserFile> queryWrapper = Wrappers.query();
            queryWrapper.eq("user_id", userId);
            queryWrapper.eq("parent_id", record.getParentId());
            queryWrapper.eq("filename", record.getFilename());
            queryWrapper.eq("del_flag", DelFlagEnum.NO.getCode());
            if (userFileService.count(queryWrapper) > 0) {
                throw new ApiException("文件: " + record.getFilename() + " 还原失败，该文件夹下面已经存在了相同名称的文件或者文件夹，请重命名之后再执行文件还原操作");
            }
        }

        records.forEach(record -> {
            record.setDelFlag(DelFlagEnum.NO.getCode());
            record.setUpdateTime(new Date());
        });

        boolean update = userFileService.updateBatchById(records);
        if (!update) {
            throw new ApiException("内部错误，文件还原失败");
        }

        RestoreFileEvent event = new RestoreFileEvent(this, fileIds);
        applicationContext.publishEvent(event);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(DeleteFileDTO requestParam) {
        List<Long> fileIds = requestParam.getFileIds();
        Long userId = requestParam.getUserId();

        QueryWrapper<UserFile> queryWrapper = Wrappers.query();
        queryWrapper.eq("user_id", userId);
        queryWrapper.in("file_id", fileIds);

        List<UserFile> records = userFileService.list(queryWrapper);
        if (CollUtil.isEmpty(records) || records.size() != fileIds.size()) {
            throw new ApiException("无权删除该文件");
        }

        // 递归查找所有子文件
        List<UserFile> allRecords = userFileService.findAllFileRecords(records);

        List<Long> userFileIds = allRecords.stream()
                .map(UserFile::getFileId)
                .collect(Collectors.toList());

        // 删除用户文件
        if (!userFileService.removeByIds(userFileIds)) {
            throw new ApiException("文件删除失败");
        }

        long sumFileSize = allRecords.stream()
                .mapToLong(file -> file.getFileSize() != null ? file.getFileSize() : 0L)
                .sum();

        userService.addSpace(userId, sumFileSize);

        // 发布删除事件
        DeleteFileEvent event = new DeleteFileEvent(this, allRecords);
        applicationContext.publishEvent(event);
    }

}
